<template>
    <el-card>
        <template #header>
            <h3>角色与权限管理</h3>
        </template>
        <!-- 搜索区域 -->
        <el-form inline align="center">
            <el-form-item label="账号" style="width: 200px">
                <el-input v-model="params.account"></el-input>
            </el-form-item>
            <el-form-item label="姓名" style="width: 200px">
                <el-input v-model="params.name"></el-input>
            </el-form-item>
            <el-form-item label="角色">
                <el-select v-model="params.role" placeholder="" style="width: 90px">
                    <el-option v-for="item in roleOptions" :key="item.value" :label="item.label" :value="item.value" />
                </el-select>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="searchUsers()">搜索</el-button>
            </el-form-item>
        </el-form>
        <!-- 表格区域 -->
        <el-table :data="user" @sort-change="handleSortChange">
            <el-table-column label="账号" prop="account" sortable="custom" align="center"></el-table-column>
            <el-table-column label="姓名" prop="name" sortable="custom" align="center"></el-table-column>
            <el-table-column label="角色" prop="role" sortable="custom" align="center">
                <template #default="scope">
                    <span v-if="scope.row.role == 1">医生</span>
                    <span v-else>管理员</span>
                </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
                <template #default="scope">
                    <el-button type="primary" @click="showSettingRoleWindow(scope.row)">角色设置</el-button>
                    <el-button type="primary"
                        @click="this.$router.push('/permission/' + scope.row.user_id)">权限设置</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页区域 -->
        <el-pagination v-if="params.total > 0" :current-page="params.currentPage" :page-size="params.pageSize"
            background layout="total, prev, pager, next" :total="params.total" @current-change="handleCurrentChange" />
    </el-card>
    <!-- 账号角色修改弹窗 -->
    <el-dialog v-model="showSettingRole" title="账号角色修改" width="500" @close="closeWindow">
        <div>
            <el-radio-group v-model="curUser.role">
                <el-radio v-for="item in roleSettingOptions" :key="item.value" :label="item.label" :value="item.value">
                    {{ item.label }}
                </el-radio>
            </el-radio-group>
        </div>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="updateRole(curUser)">确定</el-button>
                <el-button @click="showSettingRole = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
    <!-- 医生信息填写弹窗 -->
    <el-dialog v-model="showDoctorEdit" title="请填写医生信息" width="500" @close="closeWindow">
        <el-form :model="curUser" label-width="120px" :rules="rules" ref="curUserForm">
            <!-- 上传头像 -->
            <el-form-item label="头像" prop="avatar" v-show="!showAdd">
                <el-upload class="avatar-uploader" action="http://127.0.0.1:8082/upload" :show-file-list="false"
                    :on-success="handleAvatarSuccess">
                    <el-avatar v-if="curUser.user_img" shape="circle" :size="150" :fit="'cover'"
                        :src="curUser.user_img" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
            <el-form-item label="职称" prop="title">
                <el-autocomplete v-model="curUser.title" value-key="name" :fetch-suggestions="querySearchTitles"
                    clearable class="inline-input w-50" placeholder="" @select="handleSelectTitle"
                    @input="clearTitle" />
            </el-form-item>
            <el-form-item label="科室" prop="department">
                <el-autocomplete v-model="curUser.department" value-key="name"
                    :fetch-suggestions="querySearchDepartments" clearable class="inline-input w-50" placeholder=""
                    @select="handleSelectDepartment" @input="clearDepartment" />
            </el-form-item>
            <el-form-item label="医疗机构" prop="institution">
                <el-autocomplete v-model="curUser.institution" value-key="name"
                    :fetch-suggestions="querySearchHealthInstitutions" clearable class="inline-input w-50"
                    placeholder="" @select="handleSelectHealthInstitution" />
            </el-form-item>
            <el-form-item label="简介" prop="description" v-show="!showAdd">
                <el-input v-model="curUser.description"></el-input>
            </el-form-item>
            <el-form-item label="邮箱" prop="email" v-show="!showAdd">
                <el-input v-model="curUser.email"></el-input>
            </el-form-item>
            <el-form-item label="电话" prop="phone">
                <el-input v-model="curUser.phone"></el-input>
            </el-form-item>
            <el-form-item label="挂号费" prop="fee">
                <el-input-number v-model="curUser.fee" :min="0" step-strictly="true" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button type="primary" @click="updateDoctor(curUser)">保存</el-button>
                <el-button @click="showDoctorEdit = false">取消</el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script>
import { departmentFindAPI } from '@/api/department';
import { doctorInfoUpdateAPI, doctorsFindAPI } from '@/api/doctor';
import { healthInstitutionFindAPI } from '@/api/healthInstitution';
import { titleFindAPI } from '@/api/title';
import { doctorAndAdminFindAPI, roleUpdateAPI } from '@/api/user';
import { ElMessage } from 'element-plus';
export default {
    data() {
        return {
            params: {
                // 搜索关键词
                user_id: '',
                name: '',
                account: '',
                role: '',
                // 分页参数
                total: 0,
                currentPage: 1,
                pageSize: 7
            },
            user: [],
            curUser: '',
            roleOptions: [
                {
                    value: '',
                    label: '全部'
                },
                {
                    value: 1,
                    label: '医生'
                },
                {
                    value: 2,
                    label: '管理员'
                }
            ],
            roleSettingOptions: [
                {
                    value: 1,
                    label: '医生'
                },
                {
                    value: 2,
                    label: '管理员'
                }
            ],
            showSettingRole: false,
            showDoctorEdit: false,
            rules: {
                name: { required: true, message: '姓名不能为空', trigger: 'blur' },
                account: { required: true, message: '账号不能为空', trigger: 'blur' },
                email: [
                    { required: false, trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const emailRegex = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
                            if (!this.showAdd && value !== '') {
                                if (emailRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的邮箱地址'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                phone: [
                    { required: true, message: '手机号不能为空', trigger: 'blur' },
                    {
                        validator: (rule, value, callback) => {
                            const phoneRegex = /^[0-9]{11}$/;
                            if (value !== '') {
                                if (phoneRegex.test(value)) {
                                    callback();
                                } else {
                                    callback(new Error('请输入有效的手机号'));
                                }
                            }
                        },
                        trigger: 'blur'
                    }
                ],
                title: { required: true, message: '职称不能为空', trigger: 'blur' },
                department: { required: true, message: '科室不能为空', trigger: 'blur' },
                institution: { required: true, message: '医疗机构不能为空', trigger: 'change' },
                fee: { required: true, message: '挂号费不能为空', trigger: 'blur' }
            },
        }
    },
    methods: {
        loadUserList() {
            doctorAndAdminFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.user = resp.data.datas;
                    this.params.total = resp.data.total;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        searchUsers() {
            this.loadUserList();
        },
        handleCurrentChange(page) {
            this.params.currentPage = page;
            this.loadUserList();
        },
        showSettingRoleWindow(role) {
            this.curUser = role;
            this.showSettingRole = true;
        },
        updateRole(row) {
            roleUpdateAPI(row).then((resp) => {
                if (resp.data.code == 2000) {
                    this.loadUserList();
                    this.showSettingRole = false;
                    if (row.role == 1) {
                        this.showDoctorEdit = true;
                    }
                    ElMessage.success(resp.data.message);
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        closeWindow() {
            this.loadUserList();
            this.showSettingRole = false;
        },
        // 图片上传成功之后回调函数
        handleAvatarSuccess(response) {
            this.curUser.user_img = response;
        },
        updateDoctor(row) {
            this.$refs.curUserForm.validate((val) => {
                if (val) {
                    doctorInfoUpdateAPI(row).then((resp) => {
                        if (resp.data.code == 2000) {
                            this.loadDoctorInfoList();
                            this.showDoctorEdit = false;
                            ElMessage.success(resp.data.message);
                        } else {
                            ElMessage.error(resp.data.message);
                        }
                    })
                }
            })
        },
        loadDoctorInfoList() {
            healthInstitutionFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.healthInstitutions = resp.data.datas;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            departmentFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.departments = resp.data.datas;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
            titleFindAPI(this.params).then((resp) => {
                if (resp.data.code == 2000) {
                    this.titles = resp.data.datas;
                } else {
                    ElMessage.error(resp.data.message);
                }
            })
        },
        //该方法选择列表后触发
        handleSelectHealthInstitution(item) {
            this.curUser.institution_id = item.id;
        },
        //输入框获取焦点时调用的方法
        querySearchHealthInstitutions(queryString, cb) {
            let results = this.healthInstitutions;
            results = queryString
                ? results.filter(this.createFilter(queryString))
                : results;
            cb(results);
        },
        //这是当输入数据时触发的，筛选出和输入数据匹配的建议输入。
        createFilter(queryString) {
            return (item) => {
                // 确保 item 是一个字符串或对象
                if (typeof item === 'object') {
                    return JSON.stringify(item).toLowerCase().indexOf(queryString.toLowerCase()) > -1;
                }
                return item.toLowerCase().indexOf(queryString.toLowerCase()) > -1;
            };
        },
        //点击清除按钮时触发事件
        clearHealthInstitution() {
            this.params.institution_id = '';
            this.loadDoctorInfoList();
        },
        //科室下拉框
        //该方法选择列表后触发
        handleSelectDepartment(item) {
            this.curUser.department_id = item.id;
        },
        //输入框获取焦点时调用的方法
        querySearchDepartments(queryString, cb) {
            console.log(this.departments);

            let results = this.departments;
            results = queryString
                ? results.filter(this.createFilter(queryString))
                : results;
            cb(results);
        },
        //点击清除按钮时触发事件
        clearDepartment() {
            this.curUser.department_id = '';
            this.loadDoctorInfoList();
        },
        //职称下拉框
        //该方法选择列表后触发
        handleSelectTitle(item) {
            this.curUser.title_id = item.id;
        },
        //输入框获取焦点时调用的方法
        querySearchTitles(queryString, cb) {
            let results = this.titles;
            results = queryString
                ? results.filter(this.createFilter(queryString))
                : results;
            cb(results);
        },
        //点击清除按钮时触发事件
        clearTitle() {
            this.params.title_id = '';
            this.loadDoctorInfoList();
        },
        handleSortChange({ prop, order }) {
            if (order) {
                // 根据 prop 和 order 进行排序
                this.params.sortProp = prop;
                this.params.sortOrder = order === 'ascending' ? 'asc' : 'desc';
                this.loadUserList();
            } else {
                // 清除排序
                delete this.params.sortProp;
                delete this.params.sortOrder;
                this.loadUserList();
            }
        }
    },
    created() {
        this.loadUserList();
        this.loadDoctorInfoList();
    }
}
</script>

<style scoped>
.el-pagination {
    margin: 20px 0 0 450px;
    align-items: center;
}

.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 50%;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>